#include "audiomanager.h"

AudioManager::AudioManager()
{
	audioOutput = new QAudioOutput();
	audioOutput->setFrequency(FREQUENCY);
	audioOutput->setChannels(CHANNELS);
	audioOutput->setBitsPerSample(BIT_DEPTH);
    audioOutput->open( QIODevice::WriteOnly );
	audioFile = NULL;
	needPlay = false;
}
		
AudioManager::~AudioManager()
{
	stop();
	audioFile->close();
	audioOutput->close();
	qDebug() << "audioManager dismiss";
}

void AudioManager::setAudio(QString filename)
{
	//qDebug() << "AudioManager::setAudio(QString, int)";
	QDir dir = QDir::home();
	dir.cd("Documents");
	audioFile = new QFile(dir.filePath(filename));
	if (!audioFile->open(QIODevice::ReadOnly)) {
		qDebug() << "can not open file"<< filename;
	} else {
		qDebug() << filename << "loaded.";
	}
}

int AudioManager::getDuration()
{
	if (audioFile == NULL) {
		qDebug() << "no audio file loaded";
		return -1;
	} else {
		int duration = audioFile->size()/BYTE_RATE;
		if (duration%10>0) duration += 10;
		return duration;
	}
}



int AudioManager::getOffset()
{
	return audioFile->pos()/ BYTE_RATE;
}

void AudioManager::play(int offset)
{
	qDebug() << "AudioManager->play("<<offset<<")";
	stop();
	setOffset(offset);
	start();
}

void AudioManager::setOffset(int offset)
{
	qDebug() << "AudioManager->setOffset ("<<offset<<")";
	if(audioFile != NULL){
        audioFile->seek(offset * BYTE_RATE);
    }
}

void AudioManager::run()
{
	qDebug() << "AudioManager->run";
	char buffer[BYTE_RATE];
    	qint64 length;
	needPlay = true;
    while (needPlay && !audioFile->atEnd()){
        length = audioFile->read(buffer, BYTE_RATE);
        audioOutput->write(buffer, length);
        emit audioPlayingSignal(audioFile->pos()/BYTE_RATE);
	//qDebug() << "audio playing at" << audioFile->pos()/BYTE_RATE;
    }
    if(audioFile->atEnd()){
        emit audioFinishingSignal();
	stop();
    }
}

void AudioManager::stop()
{
	qDebug() << "AudioManager->stop";
	needPlay = false;
	wait(1000);
}








